/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.gift.service;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.boxin.framework.base.utils.Constants;
import com.boxin.ims.modules.gift.entity.Gift;
import com.boxin.ims.modules.gift.dao.GiftDao;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.dao.QRCodeDao;
import com.boxin.ims.modules.momarketing.entity.Project;
import com.boxin.ims.modules.momarketing.entity.QRCode;

/**
 * 礼品Service
 * @author Jakemanse
 * @version 2013-07-28
 */
@Component
@Transactional(readOnly = true)
public class GiftService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(GiftService.class);
	
	@Autowired
	private GiftDao giftDao;
	
	@Autowired
	QRCodeDao QRCodeDao;
	
	public Gift get(Long id) {
		return giftDao.findOne(id);
	}
	
	public Page<Gift> find(Page<Gift> page, Gift gift) {
		DetachedCriteria dc = giftDao.createDetachedCriteria();
		if (gift.getUser()!=null && gift.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", gift.getUser().getId()));
		}
		if (StringUtils.isNotEmpty(gift.getName())){
			dc.add(Restrictions.like("name", "%"+gift.getName()+"%"));
		}
		if (StringUtils.isNotEmpty(gift.getRemarks())){
			dc.add(Restrictions.like("remarks", "%"+gift.getRemarks()+"%"));
		}
		dc.add(Restrictions.eq("delFlag", Gift.DEL_FLAG_NORMAL));
		dc.addOrder(Order.desc("id"));
		return giftDao.find(page, dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Gift gift) {
		
		
		gift.setContent(StringEscapeUtils.unescapeHtml4(gift.getContent()));
		giftDao.save(gift);
		if(gift.getQrCode() == null || gift.getQrCode().getId()==null){
			
			//生成二维码
			QRCode qrCode = new QRCode();
			qrCode.setContent("None");
			qrCode.setJpegPath(Constants.getGiftQRCodeResourceSavePath()+System.currentTimeMillis()+""+gift.getId());
			
			QRCode savedqrCode = QRCodeDao.save(qrCode);
			
			
			String con = QRCodeUtils.generateGiftURL(gift.getId());
			qrCode.setContent(con);
			QRCodeUtils.generateQRCodeJPEG(qrCode.getContent(), qrCode.getJpegPath(), 200, 200);
			QRCodeDao.save(qrCode);		
			
			gift.setQrCode(savedqrCode);
			giftDao.save(gift);
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		giftDao.deleteById(id);
	}
	
}
